package com.ly.vcode.web;

import com.ly.util.Utils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class VcodeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
//        return HandlerInterceptor.super.preHandle(request, response, handler);
        // 用户输入的验证码
        String rcode = request.getParameter("vcode");
        // 会话中保存的验证码
        String vcode = (String) request.getSession().getAttribute("vcode");
        Long time = (Long) request.getSession().getAttribute("vcode-timeout");
        if(vcode == null){
            Utils.writeResult(0,"请先获取验证码!", null, response);
            return false;
        }
        if(time < System.currentTimeMillis()){
            request.getSession().removeAttribute("vcode");
            request.getSession().removeAttribute("vcode-timeout");
            Utils.writeResult(0,"验证码过期,请重新获取掩码!", null, response);
            return false;
        }
        if(rcode == null){
            Utils.writeResult(0,"请输入验证码!", null, response);
            return false;
        }
        if(!rcode.equalsIgnoreCase(vcode)){
            Utils.writeResult(0,"输入的验证码错误!", null, response);
            return false;
        }

        // 移除会话中的验证码
        request.getSession().removeAttribute("vcode");
        request.getSession().removeAttribute("vcode-timeout");
        // 放行请求到达目标资源(一般指控制器)
        return true;
    }
}
